﻿using System;
using System.Web;
using System.Collections.Generic;

using Token.Util;

namespace Token.Piker.Core.Security
{
    /// <summary>
    /// ajax调用处理器的父类，能简化处理流程
    /// </summary>
    public abstract class BaseAjaxHandler : BaseHandler
    {
        #region 常量声明
        /// <summary>
        /// 标识操作的参数名
        /// </summary>
        protected static string OPERATION_ID = "op";

        #endregion

        #region 成员变量

        private IDictionary<string, string> _oprationMap = new Dictionary<string, string>();
        /// <summary>
        /// 操作图,op参数的值根据此图来寻找方法，从而动态调用
        /// key为op参数的值,value为将调用的方法名
        /// </summary>
        public IDictionary<string, string> OprationMap
        {
            get { return _oprationMap; }

        }

        private string _op;
        /// <summary>
        /// 操作标识
        /// </summary>
        public string Op
        {
            get { return _op; }
            set { _op = value; }
        }

        // 执行是否成功,默认false
        private bool _isSuccess = false;
        /// <summary>
        /// 标识是否全部执行成功
        /// </summary>
        public bool IsSuccess
        {
            get { return _isSuccess; }
            set { _isSuccess = value; }
        }


        private string _message = "未知错误";
        /// <summary>
        /// 返回给调用者的信息
        /// </summary>
        public string Message
        {
            get { return _message; }
            set { _message = value; }
        }


        private string _responseText;
        /// <summary>
        /// 要返回给Ajax调用者的值，若执行成功返回，必须将IsSuccess设置为True
        /// </summary>
        public string ResponseText
        {
            get { return this._responseText; }
            set { this._responseText = value; }
        }
        #endregion

        #region RequestProcess调用流程
        /// <summary>
        /// 初始化
        /// </summary>
        private void Init()
        {
            /*
            // 初始化操作表
            OprationMap["add"] = "Add";
            OprationMap["delete"] = "Delete";
            OprationMap["update"] = "Update";
            OprationMap["list"] = "List";
            */
            // 设置返回格式
            //Context.Response.ContentType = "text/plain";

            // 设置操作标识
            Op = Context.Request[OPERATION_ID] as string;
        }


        /// <summary>
        /// 方法映射(需重写此函数)，在此方法中添加需要映射的方法
        /// </summary>
        protected virtual void Mapping()
        {

        }

        /// <summary>
        /// 打印结果
        /// </summary>
        protected virtual void Response()
        {
            //---- 打印返回的数据 若整个请求不成功，则返回错误信息
            if (!IsSuccess)
            {
                ResponseText = "{\"success\":\"false\", \"msg\":\"" + Message.Replace("'", "") + "\"}";
            }

            Context.Response.Write(ResponseText);
        }

        /// <summary>
        /// 按固定的模板返回JSON结果
        /// 如ResponseTemplate(Object data);
        /// 将把ResponseTest赋值为：{"success":"true","data":"json formatted data"}
        /// </summary>
        protected virtual void ResponseTemplate(Object data){
            ResponseText = "{\"success\":\"true\",\"data\":" + JsonHelper.Serialize(data) + "}";
        }

        #endregion

        /*
        #region 常用业务方法

        public virtual void Add()
        {

        }

        public virtual void Delete()
        {

        }

        public virtual void Update()
        {

        }

        public virtual void List()
        {

        }

        #endregion
        */

        #region IHttpHandler接口实现
        /// <summary>
        /// 定义处理流程,该方法不允许被重写
        /// </summary>
        /// <param name="context">当前上下文</param>
        public sealed override void ProcessRequest(HttpContext context)
        {
            base.ProcessRequest(context);

            // 初始化
            Init();

            // 映射方法
            Mapping();

            // ----调用相应处理方法
            if (Op != null)
            {
                try
                {
                    if (OprationMap.ContainsKey(Op))
                    {
                        InvokeHelper.ExecuteMethod(this, OprationMap[Op] as string);
                    }
                    else
                    {
                        throw new Exception("在方法映射表中不存在此操作:" + Op);
                    }
                }
                catch (Exception e)
                {
                    LogHelper.Error(e.Message,e);

                    Message = e.Message;   // 返回信息
                }
            }
            else
            {
                //不输入?op=操作名  的请求被视为非法操作
                Message = "非法操作";
            }
            // -----

            // 响应调用者,打印结果
            Response();
        }

        #endregion
    }
}